from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import datetime

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123456@127.0.0.1:3306/f1"
# 如果设置成 True (默认情况)，Flask-SQLAlchemy 将会追踪对象的修改并且发送信号。
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

# 绑定app至SQLAlchemy
db = SQLAlchemy(app)


# 用户及详情
class Users(db.Model):

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    userinfob = db.relationship('UserInfo',backref='usersa',cascade="all,delete,delete-orphan",uselist=False)


class UserInfo(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    email = db.Column(db.String(50))
    users_id =  db.Column(db.Integer,db.ForeignKey('users.id'))



if __name__ == "__main__":
   # 生成表
   # db.create_all()

   # 添加数据
   data = {'name':'zhangsan','email':'zs@qq.com'}

   # 创建用户对象
   u = Users(name = data['name'])
   db.session.add(u)
   db.session.commit()

   # 创建用户详情对象
   ui = UserInfo(email=data['email'],users_id=u.id)
   db.session.add(ui)
   db.session.commit()

   # 查询
   u = Users.query.get(1)
   print(u.name)
   # print(u.userinfob.email)

   ui = UserInfo.query.first()
   print(ui.email)
   print(ui.usersa.name)